<?php
/**
 * 
 * @todo description of this class
 * 
 * @author Alton Crossley <crossleyframework@nogahidebootstrap.com>
 * @package Crossley Framework
 *  
 * @copyright Copyright (c) 2003-2009, Nogaide BootStrap INC. All rights reserved.
 * @license BSD http://opensource.org/licenses/bsd-license.php
 * @version $Id:$
 * 
 */
/**
 * Controller for development purposes
 *
 */

class X_Controller_Handler_Generator implements X_Controller_Handler_Interface
{
    /**
     * generate html content
     *
     * @var bool
     */
    public $bHtmlContent = false;
    
    protected $_sHandlerPrefix = "Handle_Dev_";

    public function handle(X_Broker_Event_Interface $oEvent)
    {
        $sReturn = '<h4>Generation Enabled</h4>';
        
        $sHtmlFileName = $oEvent->getRawData('gen_file_name');
        $sClassName = $oEvent->getRawData('gen_class_name');

        $CreateURL = $oEvent->getBaseUrl().'/dev/';
        
        if (!empty($sHtmlFileName))
        {
            $sReturn .= "<hr>The following HTML content was expected but is not present.  Click 'create' to generate place holder file.<br>";
            $sHtmlFileName = basename($sHtmlFileName);
            $sReturn .= "HTML handler Content: <b>{$sHtmlFileName}</b> [<a href='{$CreateURL}create/html/?filename={$sHtmlFileName}'>create</a>]<br>";
        }
        if (!empty($sClassName))
        {
            $sReturn .= "<hr>The following handler was expected but is not present.  Click 'create' to generate stub code.<br>";
            $sReturn .= "Class: <b>{$sClassName}</b> [<a href='{$CreateURL}create/handler/?classname={$sClassName}'>create</a>]<hr>";
        }

        return $sReturn;

    }

    public function createHTML(X_Broker_Event_Interface $oEvent)
    {
        if (!is_dir(X_Broker::$sContentPath))
            throw new X_Controller_Exception('Content directory ('.
                X_Broker::$sContentPath.') does not exist.');
                
        if ($oEvent->getData('content') && $oEvent->getData('filename'))
        {
            $sHtmlFileName = $oEvent->getData('filename');
            $sFileContents = $oEvent->getData('content');
            
            if (file_put_contents(X_Broker::$sContentPath.basename($sHtmlFileName), $oEvent->getData('content')))
            {
                $sStaus = "File $sHtmlFileName written.";
            }
            else
            {
                $sStaus = "File write error.";
            }
        }
        else
        {
            $sStaus = null;
            $sHtmlFileName = $oEvent->getData('gen_file_name');
            $sFileContents = "<h1>Unedited Page</h1>\nYou have reached HTML File <b>{$sHtmlFileName}</b> which as not been modified with content.";
        }
        
        if (empty($sHtmlFileName)) throw new X_Controller_Exception('HTML file name not specified');
        
        $sFilePath = X_Broker::$sContentPath.$sHtmlFileName;
        
        return $this->_editFile($sFilePath, $sFileContents)."<div>$sStaus</div>";

    }
    
    private function _editFile($sFileName, $sDefalutContents = null)
    {
        $aPathInfo = pathinfo($sFileName);
        
        $sFileContents = (file_exists($sFileName)) ? file_get_contents($sFileName) : $sDefalutContents;
        
        switch ($aPathInfo['extension']) {
        	case 'html':
            	return $this->_renderHtmlEditor($sFileContents);
            	break;
        	default:
        		return $this->_renderCodeEditor($sFileContents, $aPathInfo['extension']);
        	    break;
        }
        
    }
    
    private function _renderCodeEditor($sEditString, $sSyntax = 'php')
    {
        return "
<script language='Javascript' type='text/javascript' src='/js/edit_area/edit_area_full.js'></script>
<script language='Javascript' type='text/javascript'>
	editAreaLoader.init({
		id: 'editarea'	// id of the textarea to transform	
		,start_highlight: true
		,allow_toggle: false
		,language: 'en'
		,syntax: '$sSyntax'	
		,toolbar: 'search, go_to_line, |, undo, redo, |, select_font, |, syntax_selection, |, change_smooth_selection, highlight, reset_highlight, |, help'
		,syntax_selection_allow: 'css,html,js,php,xml'
		,show_line_colors: true
	});
</script>
    
    <script type='text/javascript'' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.js'></script>
    
    <form action='' method='POST'>
        	<textarea id='editarea' name='content' cols='80' rows='15'>
        	    $sEditString
        	</textarea>
        	<br>
        	<button type='submit'>Save</button>
     </form>
        ";
    }
    
    private function _renderHtmlEditor($sEditString)
    {
        return "
<script type='text/javascript' src='/js/tiny_mce/tiny_mce.js'></script>
<script type='text/javascript'>
    tinyMCE.init({
        mode : 'exact',
		elements : 'editarea',
		mode : 'textareas',
		theme : 'advanced',
		skin : 'o2k7',
		plugins : 'style',		
		theme_advanced_toolbar_location : 'top',
		theme_advanced_toolbar_align : 'left',
		theme_advanced_statusbar_location : 'bottom',
		theme_advanced_resizing : true,
        theme_advanced_buttons1 : 'undo,redo,separator,bold,italic,underline,separator,bullist,numlist,separator,outdent,indent,separator,styleprops,anchor,cleanup,code',
	    theme_advanced_buttons2 : '',
	    theme_advanced_buttons3 : ''		
	});

</script>
 
    <script type='text/javascript'' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.js'></script>
    
        	<form action='' method='POST'>
        	<textarea id='editarea' name='content' cols='80' rows='15'>
        	    $sEditString
        	</textarea>
        	<br>
        	<button type='submit'>Save</button>
     </form>
        ";
    }

    public function createDeligate(X_Broker_Event_Interface $oEvent)
    {
        $sPrefix = str_replace('Controller', '', $sRouter);
        $sPrefix = "Handle_{$sPrefix}_";

        $sFilePath = X_Broker::$sClassPath.DIRECTORY_SEPARATOR.$sRouter.'.php';

        $sContents = <<<MOO
<?php
/**
 * simple controler that deligates
 * DESCRIBE PURPOSE HERE
 *
 */
class $sRouter extends X_Controller_Delegate
{
    protected \$_sHandlerPrefix = "$sPrefix";
}
MOO;

        $sURL =  $this->_makeClassURL($sRouter);

        if (file_exists($sFilePath))
        {
            return 'File Exists - not creating<br>';
        }
//        if (file_exists(dirname($sFilePath)) && file_put_contents($sFilePath, $sContents))
//        {
//            return 'created file successfully. '.
//                "click <a href='{$sURL}/'>here</a> to view.";
//        }

        return "creation of {$sFilePath} failed<br>";
    }

    public function createRouter(X_Broker_Event_Interface $oEvent)
    {
        if ($oEvent->getData('content') && $oEvent->getData('classname'))
        {
            $sClassName = $oEvent->getData('classname');
            $sFileContents = $oEvent->getData('content');
            
            $sFilePath = X_Broker::$sClassPath.DIRECTORY_SEPARATOR.$sClassName.'.php';
            
            if (file_put_contents($sFilePath, $sFileContents))
            {
                $sStaus = "File $sClassName written.";
            }
            else
            {
                $sStaus = "File write error.";
            }
        }
        else
        {
            $sStaus = null;
            $sClassName = $oEvent->getData('classname');
            
            if (!$sClassName) throw new X_Controller_Exception('no class name defined');
            
            $sFilePath = X_Broker::$sClassPath.DIRECTORY_SEPARATOR.$sClassName.'.php';
            
            $sPrefix = str_replace('Controller', '', $sClassName);
            $sPrefix = "Handle_{$sPrefix}_";
            
            $sFileContents = "<?php
/**
 * simple routing controler
 * DESCRIBE PURPOSE HERE
 *
 */
class $sClassName extends X_Controller_Router
{
    protected \$_sHandlerPrefix = \"$sPrefix\";
}
?>
";
        }
        
        
        return $this->_editFile($sFilePath, $sFileContents)."<div>$sStaus</div>";
    }

    public function createHandler($sClassName)
    {
        function putClass($sClassName, $sFilePath)
        {
            $sContents = "<?php
// make sure you comment this file!
class {$sClassName} implements X_Controller_Handler_Interface
{
    /**
	 * indicate if this is a secure handler 
	 *
	 * @var bool
	 */
	public \$isSecure = false;
    /**
	 * handle input
	 *
	 * @param Array Filtered SAE (Simple Array Event) Array
	 * @return variant
	 */
	public function handle(X_Broker_Event_Interface \$oEvent)
    {
        // do some stuff to handle the \$xData
        return 'You have reached an event that has not been handled yet.  (Handeler)<br>'.
            X_Debug::formatHtml(\$oEvent, '\$xData');
    }


}
";
            return file_put_contents($sFilePath, $sContents);
        }

        // TODO: handle pathing
        $sPath = X_Broker::$sClassPath;
        $aClassPath = explode('_', $sClassName);
        $sFileName = array_pop($aClassPath);
        foreach ($aClassPath as $sDIR)
        {
            $sPath .= DIRECTORY_SEPARATOR.$sDIR;
            if (!file_exists($sPath) || !is_dir($sPath))
            {
                mkdir($sPath);
            }
        }

        $sFilePath = $sPath.DIRECTORY_SEPARATOR.$sFileName.'.php';

        $sURL = $this->_makeClassURL($sClassName);

        if (file_exists($sFilePath))
        {
            return 'File Exists - not creating<br>';
        }
        if (file_exists(dirname($sFilePath)) && putClass($sClassName, $sFilePath))
        {
            return 'created file successfully. '.
                "click <a href='{$sURL}/'>here</a> to view.";
        }

        return "creation of {$sFilePath} failed<br>";
    }

    protected function _makeClassURL($sClassName)
    {
        $aName = explode('_', strtolower(str_replace('Handle_', '', str_replace('Controller', '', $sClassName))));

        $sName = implode('/', $aName);

        return '/'.$sName;
    }


    
    /**
     * @see X_Controller_Interface::getHtmlFileContent()
     *
     * @return bool
     */
    public function getHtmlFileContent()
    {    
        return $this->bHtmlContent;
    }
    
    /**
     * @see X_Controller_Interface::setHtmlFileContent()
     *
     * @param unknown_type $bHtmlFileContent
     */
    public function setHtmlFileContent($bHtmlFileContent = true)
    {    
        $this->bHtmlContent = $bHtmlFileContent;
    }

}